package com.gateon.hw.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gateon.hw.base.vo.Result;
import com.gateon.hw.client.system.req.UserAddReq;
import com.gateon.hw.client.system.req.UserListReq;
import com.gateon.hw.client.system.req.UserUpdateReq;
import com.gateon.hw.client.system.resp.UserResp;
import com.gateon.hw.system.entity.User;
import com.gateon.hw.system.mapper.MongoMapper;
import com.gateon.hw.system.mapper.UserMapper;
import com.gateon.hw.system.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * user UserServiceImpl
 * Created by leslie on 2020-3-16 13:32:07
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MongoMapper mongoMapper;

    @Override
    public Result<Page<UserResp>> list(UserListReq req) {
        User a = new User();
        BeanUtils.copyProperties(req, a);
        IPage<User> page = new Page<>(req.getCurrent(), req.getSize());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        IPage<User> r = userMapper.selectPage(page, userQueryWrapper);
        log.info(JSON.toJSONString(r));
        IPage<UserResp> fr = r.convert(user -> {
            UserResp userResp = new UserResp();
            BeanUtils.copyProperties(user, userResp);
            return userResp;
        });
        return Result.withData((Page<UserResp>) fr);
    }

    @Override
    public Result<UserResp> detail(Long id) {
        UserResp resp = new UserResp();
        User re = userMapper.selectById(id);
        BeanUtils.copyProperties(re, resp);
        return Result.withData(resp);
    }

    @Override
    public Result add(UserAddReq req) {
        User re = new User();
        BeanUtils.copyProperties(req, re);
        userMapper.insert(re);
        return Result.SUCCESS;
    }

    @Override
    public Result update(UserUpdateReq req) {
        User re = new User();
        BeanUtils.copyProperties(req, re);
        userMapper.updateById(re);
        return Result.SUCCESS;
    }

    @Override
    public Result delete(Long id) {
        userMapper.deleteById(id);
        return Result.SUCCESS;
    }

    @Override
    public Result mongoInsert(User user) {
        mongoMapper.save(user);
        return Result.SUCCESS;
    }

}